# -*- coding: utf-8 -*-
"""
Created on
@Time: 2025/1/22 11:33
@Author: Mr.Z
@contact: <QQ:40061980>
@contact: bob@pheks.com
@File: log_recorder.py
@IDE: PyCharm
@Python Version：3.12.7
"""

import os  # 导入操作系统库
import platform  # 导入系统信息库
import concurrent.futures  # 导入并行执行库
from log_recorder import setup_logger  # 导入日志记录器

# 设置日志记录器
logger = setup_logger()

def find_all_drives():
    """查找系统中的所有分区（挂载点）"""
    drives = []
    system = platform.system()
    logger.info(f"当前操作系统: {system}")

    if system == "Windows":
        # Windows 系统：查找所有盘符
        import string
        for drive in string.ascii_uppercase:
            drive_path = f"{drive}:\\"
            if os.path.exists(drive_path):
                drives.append(drive_path)
        # 操作系统版本
        logger.info(f"Windows 版本: {platform.win32_ver()[0]}")
    elif system == "Linux":
        # Linux 系统：查找所有挂载点
        with open("/proc/mounts", "r") as f:
            for line in f:
                parts = line.split()
                if len(parts) > 1:
                    mount_point = parts[1]
                    if os.path.exists(mount_point):
                        drives.append(mount_point)
        # 操作系统版本
        logger.info(f"Linux 版本: {platform.freedesktop_os_release()['NAME']}")
    else:
        logger.error(f"不支持的操作系统: {system}")
        return []

    logger.info(f"找到了 {len(drives)} 个分区/挂载点: {drives}")
    return drives

def delete_files_by_condition(drive, condition_func):
    """
    递归删除指定分区/挂载点中满足条件的文件
    :param drive: 分区/挂载点路径
    :param condition_func: 条件函数，接受文件路径作为参数，返回布尔值
    """
    for root, dirs, files in os.walk(drive):
        for file in files:
            file_path = os.path.join(root, file)
            if condition_func(file_path):
                try:
                    os.remove(file_path)
                    logger.info(f"已删除: {file_path}")
                except Exception as e:
                    logger.warning(f"无法删除 {file_path}: {e}")

def is_tmp_file(file_path):
    """判断是否为 .tmp 文件 或 .TMP 文件"""
    return file_path.lower().endswith(".tmp")

def is_large_log_file(file_path):
    """判断是否为超过 5MB 的 .log 文件"""
    if file_path.endswith(".log"):
        file_size = os.path.getsize(file_path)
        return file_size > 5 * 1024 * 1024  # 5MB
    return False

def process_drive(drive):
    """处理单个分区/挂载点的文件删除任务"""
    logger.info(f"正在扫描分区/挂载点: {drive}")

    # 删除 .tmp 文件
    logger.info(f"正在删除 {drive} 中的 .tmp 文件...")
    delete_files_by_condition(drive, is_tmp_file)

    # 删除超过 5MB 的 .log 文件
    logger.info(f"正在删除 {drive} 中超过 5MB 的 .log 文件...")
    delete_files_by_condition(drive, is_large_log_file)

def main():
    # 获取所有分区/挂载点
    drives = find_all_drives()
    if not drives:
        logger.warning("未找到任何分区/挂载点。")
        return

    # 使用线程池并发处理每个分区/挂载点
    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
        futures = [executor.submit(process_drive, drive) for drive in drives]
        for future in concurrent.futures.as_completed(futures):
            try:
                future.result()  # 获取线程执行结果
            except Exception as e:
                logger.error(f"处理分区时发生错误: {e}")

    logger.info("所有.tmp文件和超过5MB的.log文件已删除, 详情查看日志文件。")

if __name__ == "__main__":
    main()